#include <myheader.h>

#define FILENAME "1.txt"
#define BUFFER_SIZE 100

// 获取文件大小
off_t get_file_size(const char *filename) {
    struct stat st;
    if (stat("1.txt", &st) == -1) {
        return -1;
    }
    return st.st_size;
}

int main() {
    char buffer[BUFFER_SIZE];
    off_t last_size = 0;
    int fd;

    // 确保文件存在
    fd = open(FILENAME, O_CREAT | O_RDWR, 0666);
    close(fd);

    while (1) {
        // A程序输入
        printf("A: ");
        fflush(stdout);
        if (fgets(buffer, BUFFER_SIZE, stdin) == NULL) {
            perror("fgets failed");
            exit(1);
        }

        // 写入文件
        fd = open(FILENAME, O_WRONLY | O_TRUNC);
        if (fd == -1) {
            perror("open failed");
            exit(1);
        }
        write(fd, buffer, strlen(buffer));
        close(fd);

        // 等待B的回复（检测文件大小变化）
        printf("等待B的回复...\n");
        while (1) {
            off_t current_size = get_file_size(FILENAME);
            if (current_size == -1) {
                perror("stat failed");
                exit(1);
            }
            // 当文件大小改变且不为0时，认为B已写入
            if (current_size != last_size && current_size > 0) {
                last_size = current_size;
                break;
            }
            usleep(100000); // 休眠0.1秒再检查
        }

        // 读取B的回复
        fd = open(FILENAME, O_RDONLY);
        if (fd == -1) {
            perror("open failed");
            exit(1);
        }
        ssize_t n = read(fd, buffer, BUFFER_SIZE - 1);
        close(fd);
        
        if (n > 0) {
            buffer[n] = '\0';
            printf("收到B的消息: %s", buffer);
        }
    }

    return 0;
}

